import torch.nn as nn
import torchvision
# import torch.nn.functional as F

def conv3x3(in_planes, out_planes, stride=1, dilation=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=(stride, 1),
                     padding=dilation, bias=False, dilation=dilation)


def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1, norm_layer=None):
        super(BasicBlock, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d

        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out


def resnet18():

    return ResNet(BasicBlock, [2, 2, 2, 2])

class ResNet(nn.Module):

    def __init__(self, block, layers, zero_init_residual=False,
                 replace_stride_with_dilation=None,
                 norm_layer=None):
        super(ResNet, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer

        self.inplanes = 64
        self.dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        # 3 x 128 x 128 ->  64 x 64 x 64
        self.conv1 = nn.Conv2d(1, self.inplanes, kernel_size=5, stride=2, padding=2,
                               bias=False)
        self.bn1 = norm_layer(self.inplanes)
        self.relu = nn.ReLU(inplace=True)
        # 64 x 64 x 64 ->  64 x 32 x 64
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=(2, 1), padding=1)
        
        # 64 x 32 x 64 ->  64 x 16 x 64
        self.layer1 = self._make_layer(block, 64, layers[0])
        # 64 x 16 x 64 ->  128 x 8 x 64
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        # 128 x 8 x 64 ->  256 x 4 x 64                                       
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        # 256 x 4 x 64 ->  512 x 2 x 64
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])
        # 512 x 2 x 64 ->  512 x 1 x 64
        self.avgpool = nn.AdaptiveAvgPool2d((1, 64))

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                # if isinstance(m, Bottleneck):
                #     nn.init.constant_(m.bn3.weight, 0)
                if isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)

    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, (stride, 1)),
                norm_layer(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample,
                            previous_dilation, norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes,dilation=self.dilation, norm_layer=norm_layer))

        return nn.Sequential(*layers)

    def _forward_impl(self, x):
        # print(x.shape)
        x = self.conv1(x) #64
        # print(x.shape)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)#32
        # print(x.shape)

        x = self.layer1(x)#32
        # print(x.shape)
        x = self.layer2(x)#16
        # print(x.shape)
        x = self.layer3(x)#8
        # print(x.shape)
        x = self.layer4(x)#4
        # print(x.shape)

        x = self.avgpool(x)#1

        return x

    def forward(self, x):
        return self._forward_impl(x)

class BidirectionalLSTM(nn.Module):
    # Inputs hidden units Out
    def __init__(self, nIn, nHidden, nOut):
        super(BidirectionalLSTM, self).__init__()

        self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True)
        self.embedding = nn.Linear(nHidden * 2, nOut)

    def forward(self, x):
        recurrent, _ = self.rnn(x)
        T, b, h = recurrent.shape
        t_rec = recurrent.view(T * b, h)

        out = self.embedding(t_rec)  # [T * b, nOut]
        out = out.view(T, b, -1)

        return out

class CRNN(nn.Module):
    def __init__(self, imgH, cnn, n_hidden=512, leakyRelu=False):
        super(CRNN, self).__init__()
        assert imgH % 16 == 0, 'imgH has to be a multiple of 16'

        self.cnn = cnn
        self.rnn = nn.Sequential(
            BidirectionalLSTM(512, n_hidden, n_hidden),
            BidirectionalLSTM(n_hidden, n_hidden, 90))
        self.linear = nn.Linear(64 * 90, 1)

    def forward(self, x):

        # conv features
        conv = self.cnn(x)
        b = conv.shape[0]
        # print(conv.shape)

        # assert h == 1, "the height of conv must be 1"
        conv = conv.squeeze(2) # b *512 * width
        conv = conv.permute(2, 0, 1)  # [w, b, c]
        # print(conv.shape)

        out_vec = self.rnn(conv)
        out_vec = out_vec.reshape(b, -1)
        # print(out_vec.shape)
        out = self.linear(out_vec)
        # output = F.softmax(output, dim=-1)

        return out

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

def get_crnn():
    cnn = resnet18()
    
    return CRNN(128, cnn)

def get_res():
    model = torchvision.models.resnet18(pretrained=True)
    model.fc = nn.Linear(model.fc.in_features, 1)
    return nn.Sequential(model, nn.Sigmoid())
    


if __name__ == "__main__":
    import torch
    model = resnet18()
    output = model(torch.randn(size=(2,1,128,128)))
    print(output.shape)

    model = get_crnn()
    output = model(torch.randn(size=(2,1,128,128)))
    print(output.shape)

    model = get_res()
    output = model(torch.randn(size=(2,3,224,224)))
    print(output.shape)